﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;


namespace Seven.Site.Mvc.Attributes
{
    /// <summary>
    /// 异常捕获反馈处理
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class CatchExceptionAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// action类型
        /// </summary>
        private ActionType ActionType { get; set; }

        /// <summary>
        /// 是否记录异常信息
        /// </summary>
        private bool Record { get; set; }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="actionType">action类型</param>
        /// <param name="record">是否记录异常信息</param>
        public CatchExceptionAttribute(ActionType actionType, bool record = true)
        {
            this.ActionType = actionType;
            this.Record = record;
        }

        /// <summary>
        /// 在发生异常时调用
        /// </summary>
        /// <param name="filterContext">操作-筛选器上下文</param>
        public override void OnException(ExceptionContext filterContext)
        {
            string msg = filterContext.Exception.Message;
            if (this.Record)
            {
                var r = filterContext.RouteData; var context = filterContext.HttpContext;
                string c = r.Values["controller"].ToString();
                string a = r.Values["action"].ToString();
                string userName = context.User.Identity.Name;
                if (string.IsNullOrWhiteSpace(userName)) { userName = "guest"; }
                Seven.Site.Log.FileLoger.WriteLog("[" + userName + "]发生异常——异常信息：" + msg + "；所在Controller：" + c + "；所在Action：" + a + "；");
            }

            filterContext.ExceptionHandled = true;
            if (this.ActionType == Attributes.ActionType.视图)
            {
                filterContext.Result = new RedirectResult("/Blank/Index?msg=" + msg);
            }
            else if (this.ActionType == Attributes.ActionType.数据)
            {
                filterContext.Result = new Seven.Service.DataResult(new List<object>()).SerializeToJsonResult();
            }
            else if (this.ActionType == Attributes.ActionType.操作)
            {
                filterContext.Result = new Seven.Service.OperationResult(false, msg).SerializeToJsonResult();
            }
            else
            { base.OnException(filterContext); }
        }
    }
}
